/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.institution.controller;

import com.alibaba.fastjson.JSONObject;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.institution.bean.*;
import com.koron.institution.service.api.InstitutionService;
import com.koron.institution.uitls.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "Institution", description = "制度法规Api类")
@RestController
@RequestMapping(value = "/institution")
public class InstitutionController {

    @Autowired
    private InstitutionService institutionService;

    private static final Logger logger = LoggerFactory.getLogger(InstitutionController.class);

    @ApiOperation("制度列表")
    @RequestMapping(value = "/list.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "公司code", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "institutionType", value = "法规制度类型(1.集团制度，2.公司制度)", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "state", value = "状态(0.正常，1.新增审核中,2修改审核中,3废除审核中)", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "categoryId", value = "目录id", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, paramType = "query", dataType = "Integer")})
    public MessageBean<?> list(String fileName, String corpCode, Integer institutionType, Integer state, String categoryId, Integer page,
                               Integer pageSize, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        return institutionService.getInstitutionList(fileName, corpCode, institutionType, state, categoryId, page, pageSize);
    }

    @ApiOperation("导出制度清单列表")
    @RequestMapping(value = "/export.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "公司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCodeCond", value = "公司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "institutionType", value = "法规制度类型(1.法规标准，2.集团制度，3.板块制度，4.公司制度)", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "state", value = "状态(0.正常，1.新增审核中,2修改审核中,3废除审核中)", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "categoryId", value = "目录id", paramType = "query", dataType = "String"),
    })
    public HttpEntity<?> export(String fileName, String corpCode, Integer institutionType, Integer state, String categoryId,
                                @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String corpCodeCond){
        MessageBean<?> msg = institutionService.getInstitutionList(fileName, corpCode, institutionType, state, categoryId, null, null);
        if(msg.getData() == null){
            return null;
        }
        File targetFile = new File("static/excel/Institution.xlsx");
        try {
            InputStream initialStream = getClass().getClassLoader().getResourceAsStream("static/excel/Institution.xlsx");
            FileUtils.copyInputStreamToFile(initialStream, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        DataBean data = (DataBean) msg.getData();
        Map<String, Object> map = new HashMap<>();
        map.put("data", data.getList());
        return Excel.createFile("制度清单列表",targetFile,"Institution.btl",map);
    }

    @ApiOperation("制度保存草稿或者提交")
    @RequestMapping(value = "/saveOrCommit.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(value = "制度对象字符串", name = "institutionStr", required = true),
            @ApiImplicitParam(value = "文件", name = "file", required = true),
    })
    @Log(title = "制度保存",businessModule = "制度管理", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> saveOrCommit(String institutionStr, @RequestBody MultipartFile[] file, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null==user){
            MessageBean<?> msg=new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return institutionService.saveOrCommit(institutionStr, user, file);
    }


    @ApiOperation("废弃制度")
    @RequestMapping(value = "/discardInstitution.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "institutionId", value = "制度id", paramType = "query", dataType = "String")
    })
    @Log(title = "废弃制度删除",businessModule = "制度管理", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<?> discardInstitutionFile(String institutionId, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null==user){
            MessageBean<?> msg=new MessageBean<>();
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return institutionService.discardInstitution(institutionId, user);
    }

    @ApiOperation("批量修订制度")
    @RequestMapping(value = "/batchEdit.htm", method = {RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "historyListStr", value = "修改制度集合字符串", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "approverCodeListStr", value = "审批人code集合字符串", required = true, paramType = "query", dataType = "String"),
    })
    @Log(title = "批量修订制度",businessModule = "制度管理", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean<?> batchEdit(String corpCode, String historyListStr, @RequestBody MultipartFile[] files, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user
            , String approverCodeListStr, HttpServletRequest request) {

        MessageBean<?> msg = MessageBean.create(0, "success", Object.class);
        if (null==user){
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        try {
            List<InstitutionFile> institutionFileList = JSONObject.parseArray(historyListStr, InstitutionFile.class);
            if (StringUtils.isBlank(corpCode)) {
                corpCode = user.getCode();
            }
            if (institutionFileList == null || institutionFileList.size() <= 0) {
                msg.setCode(BusinessCode.EDIT_EMPTY_LIST.getCode());
                msg.setDescription(BusinessCode.EDIT_EMPTY_LIST.getDescription());
                return msg;
            }
            MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
            if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                    StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                    for (int i = 0; i < institutionFileList.size(); i++) {
                        InstitutionFile institutionFile = institutionFileList.get(i);
                        institutionFile.setFiles(standardMultipartHttpServletRequest.getFiles("files" + i));
                    }
                }
            }
            msg = institutionService.batchEdit(corpCode, institutionFileList, user, approverCodeListStr);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
        return msg;
    }

    @ApiOperation("制度历史版本列表")
    @RequestMapping(value = "/historyList.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileName", value = "文件名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "corpCode", value = "公司code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "institutionType", value = "法规制度类型(1.法规标准，2.集团制度，3.板块制度，4.公司制度)", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "version", value = "版本号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "Integer")
    })
    public MessageBean<?> historyList(String fileName, String corpCode, Integer institutionType,
                                      String version, Integer page, Integer pageSize, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        return institutionService.getHistoryList(fileName, corpCode, institutionType, version, page, pageSize);
    }


    @ApiOperation("通过制度编号获取制度历史版本列表")
    @RequestMapping(value = "/historyListByCode.htm", method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "制度编号", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "Integer")
    })
    public MessageBean<?> historyListByCode(String code, Integer page, Integer pageSize, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        return institutionService.getHistoryListByCode(code, page, pageSize);
    }

    @ApiOperation("保存文件")
    @RequestMapping(value = "/saveFile.htm", method = {RequestMethod.POST})
    public MessageBean<?> saveFile(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestBody MultipartFile[] files) {
        return institutionService.saveFile(files);
    }

    @ApiOperation("删除文件")
    @RequestMapping(value = "/deleteFile.htm", method = {RequestMethod.POST})
    public MessageBean<?> deleteFile(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String filePaths) {
        return institutionService.deleteFile(filePaths);
    }

    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(String ids) {
        return institutionService.getProcessData(ids);
    }

    @ApiOperation("根据code获取制度详情")
    @ApiImplicitParam(name = "code", value = "制度code", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getInstitutionByCode.htm", method = {RequestMethod.GET})
    public MessageBean<?> getInstitutionByCode(String ids) {
        return institutionService.getInstitutionByCode(ids);
    }
}
